from app.Model.Model import FlArticle
from sqlalchemy_serializer import SerializerMixin
from app.Vendor.Decorator import classTransaction
from app import dBSession
import math, re, os

class Article(FlArticle, SerializerMixin):

    """ 
        列表
        @param set filters 查询条件
        @param obj order 排序
        @param tuple field 字段
        @param int offset 偏移量
        @param int limit 取多少条
        @return dict
    """
    def getList(self, filters, order, field=(), offset = 0, limit = 15):
        res = {}
        res['page'] ={}
        res['page']['count'] = dBSession.query(Article).filter(*filters).count()
        res['list'] = []
        res['page']['total_page'] = self.get_page_number(res['page']['count'], limit)
        res['page']['current_page'] = offset
        if offset != 0:
            offset = (offset - 1) * limit

        if res['page']['count'] > 0:
            res['list'] = dBSession.query(Article).filter(*filters)
            res['list'] = res['list'].order_by(order).offset(offset).limit(limit).all()
        if not field:
            res['list'] = [c.to_dict() for c in res['list']]
        else:
            res['list'] = [c.to_dict(only=field) for c in res['list']]
        return res

    """
        查询全部
        @param set filters 查询条件
        @param obj order 排序
        @param tuple field 字段
        @param int $limit 取多少条
        @return dict
    """
    def getAll(self, filters, order, field = (), limit = 0):
        res = dBSession.query(Article).filter(*filters)
        if limit != 0:
            res = res.order_by(order).limit(limit).all()
        else:
            res = res.order_by(order).all()
        if not field:
            res = [c.to_dict() for c in res]
        else:
            res = [c.to_dict(only=field) for c in res]
        return res

    
    """
        获取一条
        @param set filters 查询条件
        @param obj order 排序
        @param tuple field 字段
        @return dict
    """
    def getOne(self, filters, order, field = ()):
        res = dBSession.query(Article).filter(*filters)
        res = res.order_by(order).first()
        if res == None:
            return None
        if not field:
            res = res.to_dict()
        else:
           res = res.to_dict(only=field) 
        return res
  
    """
        添加
        @param obj data 数据
        @return bool
    """
    @classTransaction
    def add(self, data):
        dBSession.add(Article(**data))
        return True

    
    """
        修改
        @param dict data 数据
        @param set filters 条件
        @return bool
    """
    @classTransaction
    def edit(self, data, filters):
        dBSession.query(Article).filter(*filters).update(data, synchronize_session=False)
        return True
    
    """
        删除
        @paramset filters 条件
        @return bool
    """
    @classTransaction
    def delete(self, filters):
        dBSession.query(Article).filter(*filters).delete(synchronize_session=False)
        return True
    
    """
        统计数量
        @param set filters 条件
        @param obj field 字段
        @return int
    """  
    def getCount(self, filters, field = None):
        if field == None:
            return dBSession.query(Article).filter(*filters).count()
        else:
            return dBSession.query(Article).filter(*filters).count(field)

    @staticmethod
    def get_page_number(count, page_size):
        count = float(count)
        page_size = abs(int(page_size))
        if page_size != 0:
            total_page = math.ceil(count / page_size)
        else:
            total_page = math.ceil(count / 5)
        return total_page

    """
        获取文本中首张图片地址
        @param  [type] content
        @return [type]
    """
    def getfirstpic(self, content):
        regex=re.compile("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i")
        matches=regex.findall(content)
        if matches:
            file_img=matches[0]
            
            if os.path.exists(file_img):
            
                return matches[0]
            
        return False


    #获取文章内容的第一张图片，并缩略图保存
    def getBodyFirstPic(self, content):
        res = ''
        imagepath = self.getfirstpic(content)
        if imagepath:
            #获取文章内容的第一张图片
            imagepath = '.'+imagepath
            
            #获取后缀名
            regex=re.compile("/\/(.+)\.(gif|jpg|jpeg|bmp|png)$/iU")
            out=regex.findall(imagepath)
            
            saveimage = './uploads/'+date('Y/m',time())+'/'+basename(imagepath,'.'+out[0])+'-lp.'+out[0]
            
            #生成缩略图
            """   $image = \think\Image::open($imagepath);
            // 按照原图的比例生成一个最大为240*180的缩略图
            $image->thumb(sysconfig('CMS_IMGWIDTH'), sysconfig('CMS_IMGHEIGHT'))->save($saveimage);
            
            #缩略图路径
            $res = '/uploads/'.date('Y/m',time()).'/'.basename($imagepath,'.'.$out[2][0]).'-lp.'.$out[2][0];      """
        return res